<template>
  <!-- 角色表单对话框 -->
  <zy-base-dialog
    :title="dialogTitle"
    v-model:visible="dialogVisible"
    v-model:fullscreen="dialogFullscreen"
    width="600px"
    :close-on-click-modal="false"
    @close="handleDialogClose"
    @cancel="handleDialogClose"
    @submit="handleSubmit"
    :submit-loading="submitLoading"
  >
    <el-form
      ref="roleFormRef"
      :model="roleForm"
      :rules="roleFormRules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" />
      </el-form-item>
      <el-form-item label="角色类型" prop="roleType">
        <el-select v-model="roleForm.roleType" placeholder="请选择角色类型" style="width: 100%">
          <el-option label="系统角色" value="SYSTEM" />
          <el-option label="业务角色" value="BUSINESS" />
          <el-option label="自定义角色" value="CUSTOM" />
        </el-select>
      </el-form-item>
      <el-form-item label="系统编码" prop="systemCode">
        <el-input v-model="roleForm.systemCode" placeholder="请输入系统编码" />
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-switch
          v-model="roleForm.isEnable"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>
    </el-form>
  </zy-base-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElSwitch } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { addRoleApi, updateRoleApi, SysRole } from '@/api/system/role'
// Business 组件已全局注册，无需导入
import { isResponseSuccess } from '@/utils/httpStatus'

// Props
interface Props {
  visible: boolean
  roleData?: SysRole
  isEdit?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  roleData: undefined,
  isEdit: false
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  success: []
}>()

// 响应式数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const dialogFullscreen = ref(false)

const roleFormRef = ref<FormInstance>()

// 角色表单
const roleForm = reactive<SysRole>({
  roleId: undefined,
  roleName: '',
  roleCode: '',
  roleType: 'BUSINESS',
  systemCode: '',
  isEnable: 1
})

// 表单验证规则
const roleFormRules: FormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 20, message: '角色编码长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleType: [{ required: true, message: '请选择角色类型', trigger: 'change' }],
  systemCode: [{ required: true, message: '请输入系统编码', trigger: 'blur' }]
}

// 监听 visible 变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal
    if (newVal) {
      dialogTitle.value = props.isEdit ? '编辑角色' : '新增角色'
      if (props.isEdit && props.roleData) {
        Object.assign(roleForm, props.roleData)
      } else {
        resetRoleForm()
      }
    }
  },
  { immediate: true }
)

// 监听 dialogVisible 变化，同步到父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 提交表单
const handleSubmit = async () => {
  if (!roleFormRef.value) return

  try {
    await roleFormRef.value.validate()
    submitLoading.value = true

    let result
    if (roleForm.roleId) {
      result = await updateRoleApi(roleForm.roleId, roleForm)
      if (isResponseSuccess(result)) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        emit('success')
      } else {
        ElMessage.error('更新失败')
      }
    } else {
      result = await addRoleApi(roleForm)
      if (isResponseSuccess(result)) {
        ElMessage.success('新增成功')
        dialogVisible.value = false
        emit('success')
      } else {
        ElMessage.error('新增失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置角色表单
const resetRoleForm = () => {
  Object.assign(roleForm, {
    roleId: undefined,
    roleName: '',
    roleCode: '',
    roleType: 'BUSINESS',
    systemCode: '',
    isEnable: 1
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetRoleForm()
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
